package rs.networx.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import rs.networx.enumeration.FriendRequestCategory;
import rs.networx.dao.FriendRequestDao;
//import rs.networx.dao.NottificationCategory;
import rs.networx.dao.NottificationDao;
import rs.networx.dao.PersonDao;
import rs.networx.entity.FriendRequest;
import rs.networx.entity.Nottification;
import rs.networx.entity.Person;

public class AcceptFriendRequestServlet extends HttpServlet {

	private static final long serialVersionUID = -7998918674008251189L;
	
	@EJB
	private PersonDao personDao;
	
	@EJB
	private FriendRequestDao friendRequestDao;
	
	@EJB
	private NottificationDao nottificationDao;

	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;
	
	private String requestFromID;
	private Integer intRequestFromID;
	private Person requestFromPerson;
	
	private String friendRequestID;
	private Integer intFriendRequestID;
	private FriendRequest friendRequest;
	
	private Integer friendRequestsCount;
	private Integer nottificationsCount;
	
	private Set<Person> loggedUsersFriendsSet;
	private List<Person> loggedUsersFriendsList;
	
	private Set<Person> requestFromPersonsFriendsSet;
	private List<Person> requestFromPersonsFriendsList;
	
	private ArrayList<Person> mutualFriends;
	
	private boolean pass;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		System.out.println("LOADED: AcceptFriendRequestServlet");
		
		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());
		
		HttpSession session = request.getSession();
		loggedUser = (Person)session.getAttribute("logovaniUser");
		
		try {	
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();
			System.out.println(username + "  " + password + "  " + intLoggedUserID);
			
			requestFromID = request.getParameter("personID");
			friendRequestID = request.getParameter("friendRequestID");
			System.out.println(requestFromID + "  " + friendRequestID);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
			intRequestFromID = Integer.parseInt(requestFromID);
			intFriendRequestID = Integer.parseInt(friendRequestID);
			System.out.println(intRequestFromID + "  " + intFriendRequestID);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		
		// dobavljamo friend request iz baze...
		friendRequest = friendRequestDao.findById(intFriendRequestID);
		
		if(loggedUser != null){
			// funkcija personDao.addToFriends() dodaje requestFromPerson u listu prijatelja loggedUsera i isto tako dodaje i...
			// loggedUsera u listu prijatelja requestFromPerson-a...
			pass = personDao.addToFriends(intFriendRequestID);
			// ako je dodao u prijatelje(tj. ako nisu prijatelji)...
			if(pass){
				if(friendRequest != null){
					// postavljamo status zahteva na confirmed...
					friendRequest.setStatus(2);
					friendRequestDao.merge(friendRequest);
					
					// nadjemo osobu koja je poslala friend request...
					requestFromPerson = personDao.findById(intRequestFromID);
					
					if(requestFromPerson != null){
						// trebalo bi da dodamo novu notifikaciju za logged usera da je on sada prijatelj sa requestFromPerson-om...
						// adding nottification to logged user...
						Nottification nottification = new Nottification();
						nottification.setOwner(loggedUser);
						nottification.setTargetID(friendRequest.getId());
						nottification.setType(1);
						nottification.setViewed(false);
						nottification.setLink("You Are Now Friends With: " + 
											  "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
											  " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + ".");	
						nottificationDao.persist(nottification);
						
						// i sada bi trebalo bi da dodamo novu notifikaciju za requestFromPerson-a da je on sada prijatelj sa logged user-om...
						// adding nottification to requestFromPerson...
						Nottification nottification2 = new Nottification();
						nottification2.setOwner(requestFromPerson);
						nottification2.setTargetID(friendRequest.getId());
						nottification2.setType(1);
						nottification2.setViewed(false);
						nottification2.setLink("You Are Now Friends With: " + 
											   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
											   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + ".");	
						nottificationDao.persist(nottification2);
						
						// sada bi trebalo svim prijateljima logged usera i svim prijateljima requestFromPerson-a poslati notifikacije...
						// da su oni sada prijatelji...
						
						// trebalo bi dodati i po notifikaciju za svakog prijatelja logged usera da je on sada prijatelj sa requestFromPerson-om...
						loggedUsersFriendsSet = personDao.getFriends(intLoggedUserID);
						System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
						
						if(loggedUsersFriendsSet == null || loggedUsersFriendsSet.size() == 0){
							// znaci da nema prijatelja, pa idemo dalje...
							System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
							
						}else if(loggedUsersFriendsSet != null && loggedUsersFriendsSet.size() > 0){
							loggedUsersFriendsList = new ArrayList<Person>();
							
							Iterator<Person> iter = loggedUsersFriendsSet.iterator();
						    while(iter.hasNext()){
						    	loggedUsersFriendsList.add((Person)iter.next());
						    }
						    System.out.println("loggedUsersFriendsList: " + loggedUsersFriendsList.size());
						    
						    // sada treba za svakog prijatelja logged usera napravimo po notifikaciju...
							for(int i = 0; i < loggedUsersFriendsList.size(); i++){
								// adding nottification to logged users friends(koji nisu mutual friends)...
								if(loggedUsersFriendsList.get(i).getId().equals(intRequestFromID)){
									continue;
								}
								if(personDao.checkIfMutual(intLoggedUserID, intRequestFromID, loggedUsersFriendsList.get(i).getId()) == false){
									
									Nottification nottification3 = new Nottification();
									nottification3.setOwner(loggedUsersFriendsList.get(i));
									nottification3.setTargetID(friendRequest.getId());
									nottification3.setType(2);
									nottification3.setViewed(false);
									nottification3.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
														   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
														   " Is Now Friends With " + 
														   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
														   " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + ".");
									nottificationDao.persist(nottification3);
								}								
							}
						}
						
						// trebalo bi dodati i po notifikaciju za svakog prijatelja requestFromPerson-a da je on sada prijatelj sa logged user-om...
						requestFromPersonsFriendsSet = personDao.getFriends(intRequestFromID);
						System.out.println("selectedPersonsFriendsSet: " + requestFromPersonsFriendsSet.size());
						
						if(requestFromPersonsFriendsSet == null || requestFromPersonsFriendsSet.size() == 0){
							// znaci da nema prijatelja, pa idemo dalje...
							System.out.println("requestFromPersonsFriendsSet: " + requestFromPersonsFriendsSet.size());
							
						}else if(requestFromPersonsFriendsSet != null && requestFromPersonsFriendsSet.size() > 0){
							requestFromPersonsFriendsList = new ArrayList<Person>();
							
							Iterator<Person> iter = requestFromPersonsFriendsSet.iterator();
						    while(iter.hasNext()){
						    	requestFromPersonsFriendsList.add((Person)iter.next());
						    }
						    System.out.println("selectedPersonsFriendsList: " + requestFromPersonsFriendsList.size());
						    
						    // sada treba za svakog prijatelja requestFromPerson-a da napravimo po notifikaciju...
							for(int i = 0; i < requestFromPersonsFriendsList.size(); i++){
								// adding nottification to requestFromPersons friends(koji nisu mutual friends)...
								if(requestFromPersonsFriendsList.get(i).getId().equals(intLoggedUserID)){
									continue;
								}
								if(personDao.checkIfMutual(intRequestFromID, intLoggedUserID, requestFromPersonsFriendsList.get(i).getId()) == false){
									
									Nottification nottification4 = new Nottification();
									nottification4.setOwner(requestFromPersonsFriendsList.get(i));
									nottification4.setTargetID(friendRequest.getId());
									nottification4.setType(2);
									nottification4.setViewed(false);
									nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
											   			   " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + 
											   			   " Is Now Friends With " + 
											   			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
											   			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + ".");
									nottificationDao.persist(nottification4);
								}							
							}
						}
						
						// sada treba i za sve mutual friends da posaljemo po notifikaciju...
						mutualFriends = personDao.getAllMutualFriends(intLoggedUserID, intRequestFromID);
						if(mutualFriends != null && mutualFriends.size() > 0){
							// saljemo notifikacije...
							System.out.println("mutualFriends: " + mutualFriends.size());
							
							for(int i = 0; i < mutualFriends.size(); i++){
								// adding notifications to all mutual friends...
								Nottification nottification4 = new Nottification();
								nottification4.setOwner(mutualFriends.get(i));
								nottification4.setTargetID(friendRequest.getId());
								nottification4.setType(2);
								nottification4.setViewed(false);
								nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + requestFromPerson.getId() + "\"" + 
										   			   " target=\"_blank\"" + ">" + requestFromPerson.getFirstName() + " " + requestFromPerson.getLastName() + "</a>" + 
										   			   " And " + 
										   			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
										   			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
										   			   " Are Now Friends.");
								nottificationDao.persist(nottification4);
							}
						}else if(mutualFriends == null || mutualFriends.size() == 0){
							// ne saljemo nista...
							System.out.println("mutualFriends: " + mutualFriends.size());
						}
						
						// sada dobavljamo i notifikacije za datog ulogovanog korisnika ako ih ima...
						nottificationsCount = nottificationDao.getNottificationsCountForLoggedUser(loggedUser);
						System.out.println("nottificationsCount: " + nottificationsCount);
											
						// sada dobavljamo neodgovorene zahteve za prijateljstvo ako ih ima...
						friendRequestsCount = friendRequestDao.getfriendRequestsCountForLoggedUser(loggedUser);
						System.out.println("friendRequestsCount: " + friendRequestsCount);
						
						// i postavljamo nonviewed notifikacije na sesiju(ako ih ima)...
						session.setAttribute("nottificationsCount", nottificationsCount);
						
						// i postavljamo te neodgovorene zahteve za prijateljstvo (ako ih ima) na sesiju...
						session.setAttribute("friendRequestsCount", friendRequestsCount);
						
						response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
						return;
						
					}else if(requestFromPerson != null){
						// znaci da je doslo do greske...
						response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
						return;
					}
				}else if(friendRequest == null){
					// znaci da je doslo do greske...
					response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
					return;
				}
			}else if(!pass){
				// znaci da vec jesu prijatelji pa postavljamo status zahteva na confirmed...
				friendRequest.setStatus(2);
				friendRequestDao.merge(friendRequest);
				
				response.sendRedirect("ViewFriendRequestsLoggedUserServlet");
				return;
			}
		}else if(loggedUser == null){
			request.getRequestDispatcher("Welcome.jsp").forward(request, response);
			return;
		}	
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
	
	
}
